var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var app = getApp();
var isOnLoad = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataLoaded: false,
    cartNum: 0, //购物车内商品数量
    totalPrice: '0.00',

    isLogin: true,

    //购物车弹出浮层
    panel: {
      isShow: false,
      aimation: {},
      opacityAnimation: {},
    },

    cateList: [],
    curCate: null,
    cartList: [],

    isSkuShow: false,
    curGoods: null,
    curSkuItem: null,

    submiting: false,
  },

  onShareAppMessage: function() {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/shopIndex/shopIndex"
    }
  },

  onLoad: function(options) {
    options = util.parseOptions(options);

    var {
      deskNum,
    } = options;

    isOnLoad = true;
    this._deskNum = deskNum;
    this.isFlashCart = false; //页面展示时是否刷新购物车

    if (deskNum) {
      wx.setNavigationBarTitle({
        title: deskNum + '号桌',
      });
    }

    common.initApp({
      loginSuc: () => {
        this.setData({
          isLogin: !!app.getUserSid()
        });

        this._pageList = [];
        this._initPage();
      }
    });
  },

  onShow() {
    if (!isOnLoad) {
      this.isFlashCart = false;
      this._initCartGoods();
    }

    isOnLoad = false;

    this.setData({
      isLogin: !!app.getUserSid()
    });

    // if (this.isFlashCart) {
    //   this.isFlashCart = false;
    //   this._initPage();
    // }
  },

  onLoginSuc() {
    this.setData({
      isLogin: true
    });
    this._initCartGoods();
  },

  _showLogin() {
    this.setData({
      isLoginShow: true
    });
  },

  _initPage() {
    this._getCateList(() => {
      this._getCartGoods(() => {
        var curCate = this.data.curCate;
        curCate && this._getGoodsList(curCate.category_id);
      });
    });
  },

  _initCartGoods() {
    this._getCartGoods(() => {
      var curCate = this.data.curCate;
      curCate && this._getGoodsList(curCate.category_id);
    });
  },

  /**
   * 初始化页面
   */
  _getCateList(cb) {
    ajax.G('/openapi/CCategory/getCategory', {}, (result) => {
      var cateList = result.result.catList || [];
      var firCate = cateList[0];

      if (firCate) {
        firCate.selected = true;
      }

      cateList.forEach((cate, i) => {
        cate.cateIndex = i;
      });

      this.setData({
        curCate: firCate,
        cateList
      });
      cb && cb();
    });
  },

  /**
   * 获取对应分类的商品列表
   * @param  {[type]} cateId [description]
   * @return {[type]}        [description]
   */
  _getGoodsList(cateId) {
    // var pageObj = this._pageList[cateId];

    // if (!pageObj) {
    //   pageObj = {
    //     page: 1,
    //     pageLoadAll: false,
    //   };
    //   this._pageList[cateId] = [pageObj];
    // } else {

    // }
    ajax.G('/openapi/CGoods/getGoodsListByCatId', {
      catId: cateId,
      // page: pageObj.page,
    }, (result) => {
      var {
        cateList = [],
          cartList = []
      } = this.data;
      var goodsList = result.result.goodsList || [];
      var curCate;

      cateList.forEach((cate) => {
        if (cate.category_id == cateId) {
          cate.selected = true;
          curCate = cate;
        } else {
          cate.selected = false;
        }
      });

      goodsList.forEach((goods, i) => {
        goods.goodsIndex = i;
        goods.cateIndex = curCate.cateIndex;
        //设置goodsList在购物车中数量
        cartList.forEach((cGoods) => {
          if (goods.id == cGoods.goodsId) {
            goods.num = parseInt(goods.num || 0) + parseInt(cGoods.amount); //购物车中数量
          }
        });
        //只有一组sku的商品，做为默认选中sku
        let skuJson = JSON.parse(goods.skuJson);
        goods.multiSku = skuJson.length > 1;
        if (skuJson.length == 1) {
          goods.selSkuId = skuJson[0].skuId;
          goods.selSkuText = this._formatSkuText(skuJson[0].skuValue);
        }
      });

      if (curCate) {
        curCate.goodsList = goodsList;
      }
      this.setData({
        dataLoaded: true,
        cateList,
        curCate,
      });
    });
  },

  _formatSkuText(skuValue) {
    skuValue = JSON.parse(skuValue);
    var keys = Object.keys(skuValue);
    var skuText = '';

    keys.forEach((key, i) => {
      skuText += skuValue[key] + (i == keys.length - 1 ? '' : ' / ');
    });
    return skuText;
  },

  _getCartGoods(cb) {
    this.setData({
      cartList: []
    });
    if (!this.data.isLogin) {
      cb && cb();
      this._showLogin();
      return;
    }

    ajax.P('/openapi/CCart/cart', {}, (data) => {
      var cartList = data.result.cartList || [];

      cartList.forEach((cartGoods) => {
        cartGoods.skuText = this._formatSkuText(cartGoods.skuValue);
      });
      this.setData({
        cartList
      });
      this._getTotalPrice();
      cb && cb();
    }, (data) => {
      if (data.code == 107) {
        this._showLogin();
      } else {
        data.msg && util.alert(data.msg);
      }
      cb && cb();
    }, true);
  },

  _getCateById(cateList, cateId) {
    var selectedCate;

    cateList.some((cate) => {
      if (cate.category_id == cateId) {
        selectedCate = cate;
        return true;
      }
    });
    return selectedCate;
  },

  /**
   * 切换分类标签
   */
  _switchTag(e) {
    this._getGoodsList(e.currentTarget.dataset.cateId);
  },

  /**
   * 增加数量
   */
  _plus: function(e) {
    this._plusCore(e.currentTarget.dataset, 'add');
  },

  _minus(e) {
    var {
      isMulti
    } = e.currentTarget.dataset;

    if (isMulti) {
      util.alert('多规格商品只能去购物车删除哦');
      return;
    }
    this._plusCore(e.currentTarget.dataset, 'minus');
  },

  /**
   * 减少数量
   */
  _minusByCart: function(e) {
    this._plusCore(e.currentTarget.dataset, 'minus');
  },

  _plusCore({
    cateId, //必选
    goodsId, //必选
    num, //必选
    cateIndex, //可选，查找索引，辅助作用，加快查找速度
    index, //可选，查找索引，辅助作用，加快查找速度
    skuId, //可选
    skuText, //可选
    skuPrice, //可选
  }, type) {
    if (!this.data.isLogin) {
      this._showLogin();
      return;
    }
    var {
      curCate,
      cateList,
      cartList
    } = this.data;
    var goods, updateCate, cartGoods, cartGoodsIndex;
    var addNum = parseInt((type == 'minus' ? '-' : '+') + 1);

    num = parseInt(num || 0) + addNum;
    if (num < 0) {
      num = 0;
    }

    // 更新商品数量
    if (cateIndex != undefined && index != undefined) { //有索引，则按索引查找
      goods = (cateList[cateIndex]['goodsList'] || [])[index];
    } else {
      cateList.some((cate) => { //无索引，则查找所有商品
        var goodsList = cate['goodsList'];

        if (!goodsList) {
          return false;
        }
        return goodsList.some((g) => {
          if (g.id == goodsId) {
            goods = g;
            return true;
          }
        });
      });
    }
    if (goods) {
      if (num > goods.amount) {
        util.alert('库存不足');
        return false;
      }
      goods.num = parseInt(goods.num || 0) + addNum;

      skuId = skuId || goods.selSkuId;
      skuText = skuText || goods.selSkuText;
      skuPrice = skuPrice || goods.sale_price;
    }

    // 更新分类数量
    if (cateIndex != undefined) {
      updateCate = cateList[cateIndex];
    } else {
      cateList.some((cate) => {
        if (cate.category_id == cateId) {
          updateCate = cate;
          return true;
        }
        if (cate.sub_category) {
          var isInSub = cate.sub_category.some((subCate) => {
            if (subCate.category_id == cateId) {
              return true;
            }
          });
          if (isInSub) {
            updateCate = cate;
            return true;
          }
        }
      });
    }
    if (updateCate) {
      updateCate.num = parseInt(updateCate.num || 0) + addNum;
    }

    // 更新购物车商品数量
    var isInCart = cartList.some((cGoods, i) => {
      if (cGoods.goodsId == goodsId && cGoods.skuId == skuId) {
        cartGoods = cGoods;
        cartGoodsIndex = i;
        return true;
      }
    });
    if (isInCart) { //在购物车中
      if (num <= 0) {
        cartList.splice(cartGoodsIndex, 1);
        this._delGoods(cartGoods.id);
      } else {
        cartGoods.amount = num;
        cartGoods.totalPrice = num * parseFloat(cartGoods.salePrice);
        this._modifyAmount(cartGoods.id, num);
      }
    } else { //不在购物车中
      cartList.push({
        goodsId: goods.id,
        amount: 1,
        name: goods.name,
        skuText: skuText,
        skuId: skuId,
        salePrice: skuPrice,
        totalPrice: skuPrice,
        categoryId: goods.category_id,
        cateIndex: goods.cateIndex,
        goodsIndex: goods.goodsIndex
      });
      this._addCart(goods.id, skuId || goods.selSkuId);
    }

    // 重取curCate
    cateList.some((cate) => {
      if (cate.category_id == curCate.category_id) {
        curCate = cate;
        return true;
      }
    });

    this.setData({
      curCate,
      cateList,
      cartList,
    });

    this._getTotalPrice();
  },

  /**
   * 清空购物车
   */
  _clearCart() {
    util.confirm('清空购物车？', () => {
      ajax.P('/openapi/CCart/delAllCart', {}, (result) => {
        var {
          cateList,
          curCate
        } = this.data;

        cateList.forEach((cate) => {
          cate.num = 0;

          cate.goodsList && cate.goodsList.forEach((goods) => {
            goods.num = 0;
          });

          if (curCate.category_id == cate.category_id) {
            curCate = cate;
          }
        });

        this.setData({
          cartList: [],
          cateList,
          curCate
        });

        this._getTotalPrice();
        this._closePanel();
      });
    });
  },


  /**
   * 计算总价
   */
  _getTotalPrice() {
    var cartList = this.data.cartList;
    var totalPrice = 0;
    var cartNum = 0;

    cartList.forEach((cartGoods) => {
      var amount = parseInt(cartGoods.amount);
      var salePrice = parseFloat(cartGoods.salePrice);

      cartNum += amount;
      totalPrice += amount * salePrice;
    });

    this.setData({
      cartNum,
      totalPrice: totalPrice.toFixed(2)
    });
  },

  /**
   * 添加到购物车
   * @param {[type]} goodsId [description]
   */
  _addCart(goodsId, skuId) {
    ajax.P('/openapi/CCart/add', {
      goodsId,
      skuId,
      amount: 1,
    }, (data) => {
      var {
        cartId,
      } = data.result;
      var {
        cartList
      } = this.data;

      cartList.some((cartGoods) => {
        if (cartGoods.goodsId == goodsId && cartGoods.skuId == skuId) {
          cartGoods.id = cartId;
          return true;
        }
      });
      this.setData({
        cartList
      });
    }, (data) => {
      if (data.code == 107) {
        this._showLogin();
      } else {
        data.msg && util.alert(data.msg);
      }
    }, true);
  },

  /**
   * 修改购物车数量
   */
  _modifyAmount(cartId, num) {
    ajax.P('/openapi/CCart/modifyAmount', {
      id: cartId,
      number: num,
    }, function(data) {}, (data) => {
      if (data.code == 107) {
        this._showLogin();
      } else {
        data.msg && util.alert(data.msg);
      }
    }, true);
  },

  /**
   * 从购物车删除
   */
  _delGoods(cartId) {
    ajax.P('/openapi/CCart/del', {
      id: cartId,
    }, function(data) {}, function() {});
  },

  /**
   * 结算
   */
  _payOrder() {
    var _self = this;
    var cartList = _self.data.cartList;
    var cartIds = [];
    var goodsIds = [];
    var skuIds = [];
    var amounts = [];

    cartList.forEach(function(goods) {
      if (goods.amount && goods.amount > 0) {
        cartIds.push(goods.id);
        goodsIds.push(goods.goodsId);
        skuIds.push(goods.skuId);
        amounts.push(goods.amount);
      }
    });

    if (goodsIds.length == 0) {
      util.alert('您还没有选择商品哦');
      return;
    }
    _self.setData({
      submiting: true
    })
    ajax.P('/openapi/CHome/showQuickBuy', {
      cartId: cartIds,
      goodsId: goodsIds,
      skuId: skuIds,
      amount: amounts
    }, function(data) {
      _self.isFlashCart = true;
      wx.navigateTo({
        url: '/pages/confirmOrder/confirmOrder?cartId=' + JSON.stringify(cartIds) + '&goodsId=' + JSON.stringify(goodsIds) + '&skuId=' + JSON.stringify(skuIds) + '&amount=' + JSON.stringify(amounts) + (_self._deskNum ? ('&deskNum=' + _self._deskNum) : ''),
      })
      _self.setData({
        submiting: false
      })
    }, function() {
      _self.setData({
        submiting: false
      })
    });
  },

  /**
   * 显示/隐藏浮层
   */
  _toggle() {
    if (this.data.panel.isShow) {
      this._closePanel();
    } else {
      this._showPanel();
    }
  },

  /**
   * 展示购物车浮层
   */
  _showPanel(ty) {
    var $this = this;
    var panel = this.data.panel;

    if (this.data.cartList.length == 0) {
      return;
    }

    $this.animation = wx.createAnimation({
      duration: 400,
      timingFunction: "ease-out"
    });
    $this.opacityAnimation = wx.createAnimation({
      duration: 400,
      timingFunction: "ease-out"
    });

    panel.isShow = true;
    $this.setData({
      panel
    });

    setTimeout(function() {
      $this.animation.translateY(0).step();
      $this.opacityAnimation.opacity(1).step();

      panel.animation = $this.animation.export();
      panel.opacityAnimation = $this.opacityAnimation.export();

      $this.setData({
        panel
      });
    }, 0);
  },

  /**
   * 关闭购物车浮层
   */
  _closePanel() {
    var $this = this;
    var panel = this.data.panel;

    $this.animation.translateY('100%').step();
    $this.opacityAnimation.opacity(0).step();

    panel.animation = $this.animation.export();
    panel.opacityAnimation = $this.opacityAnimation.export();

    $this.setData({
      panel
    })
    setTimeout(function() {
      panel.isShow = false;
      $this.setData({
        panel
      });
    }, 400)
  },

  _showSkuPanel(e) {
    var {
      cateIndex,
      index
    } = e.currentTarget.dataset;
    var {
      cateList,
      curGoods
    } = this.data;
    var goods = cateList[cateIndex].goodsList[index];

    if (goods && goods.skuList) {
      curGoods = goods;
      curGoods.isSelSkuComplete = this._checkSelSkuComplete(goods.skuList);
    }

    this.setData({
      isSkuShow: true,
      curGoods: goods
    });

    if (!goods.skuList) {
      this._setSkuList();
    } else {
      this._setSkuItem();
    }
  },

  _closeSkuPanel() {
    this.setData({
      isSkuShow: false
    });
  },

  _selSkuOk() {
    var {
      curGoods,
      cateList
    } = this.data;
    if (!curGoods.isSelSkuComplete) {
      return;
    }
    var curSkuItem = curGoods.curSkuItem;
    var skuList = curGoods.skuList;
    var goods = cateList[curGoods.cateIndex].goodsList[curGoods.goodsIndex];

    if (goods) {
      goods.skuList = skuList;
    }

    this._plusCore({
      cateId: curGoods.category_id, //必选
      goodsId: curGoods.id, //必选
      num: curGoods.num || 0, //必选
      cateIndex: curGoods.cateIndex, //可选，查找索引，辅助作用，加快查找速度
      index: curGoods.goodsIndex, //可选，查找索引，辅助作用，加快查找速度
      skuId: curSkuItem.skuId,
      skuText: curSkuItem.skuText,
      skuPrice: curSkuItem.price,
    }, 'add');

    this._closeSkuPanel();

    this.setData({
      cateList
    });
  },

  /**
   * 重组sku列表数据结构
   */
  _setSkuList() {
    var curGoods = this.data.curGoods;
    var goodsSku = curGoods.goodsSku;
    var skuList = curGoods.skuList || [];

    Object.keys(goodsSku).forEach(function(key) {
      var skuArr = goodsSku[key];
      var skuItem = {
        text: key,
        skuArr: [],
      }

      skuArr.forEach(function(text, index) {
        skuItem.skuArr.push({
          text: text,
          // selected: index == 0 ? true : false
          selected: false
        })
      });
      skuList.push(skuItem)
    });

    curGoods.skuList = skuList;

    this.setData({
      curGoods
    });
  },

  /**
   * 设置当前选中sku
   */
  _setSkuItem() {
    var curGoods = this.data.curGoods;
    var skuList = curGoods.skuList || [];
    var skuJson = JSON.parse(curGoods.skuJson);
    var curSkuItem = null;
    var selectedObj = {};

    skuList.forEach(function(group) {
      group.skuArr.some(function(skuItem) {
        if (skuItem.selected) {
          selectedObj[group.text] = skuItem.text;
          return true;
        }
      });
    });

    skuJson.some((sku) => {
      if (sku.skuValue == JSON.stringify(selectedObj)) {
        curSkuItem = {
          skuId: sku.skuId,
          price: sku.price,
          amount: sku.amount,
          skuValue: sku.skuValue,
          skuText: this._formatSkuText(sku.skuValue)
        };
        return true;
      }
    });
    curGoods.curSkuItem = curSkuItem;
    this.setData({
      curGoods
    });
  },

  /**
   * 选择sku
   */
  _selectSku(evt) {
    var {
      groupIndex,
      skuIndex,
      isDisabled,
      isSelected
    } = evt.currentTarget.dataset;
    if (isDisabled) {
      return;
    }
    var curGoods = this.data.curGoods;
    var skuList = curGoods.skuList || [];
    var groupObj = skuList[groupIndex];

    groupObj.skuArr.some(function(sku, index) {
      if (isSelected) {
        if (skuIndex == index) {
          sku.selected = false;
          return true;
        }
      } else {
        sku.selected = index == skuIndex;
        return false;
      }
    });

    this._setNoSelectedSkus(skuList);
    this._setSelectedSkus(skuList);
    curGoods.isSelSkuComplete = this._checkSelSkuComplete(skuList);

    this.setData({
      curGoods
    });

    this._setSkuItem();
  },

  /**
   * 检查是否有未选sku
   * @return {[type]} [description]
   */
  _checkSelSkuComplete(skuList = []) {
    var hasNoSelected = skuList.some((group) => {
      var hasSelected = group.skuArr.some(function(skuItem) {
        if (skuItem.selected) {
          return true;
        }
      });
      if (!hasSelected) {
        return true;
      }
    });
    return !hasNoSelected;
  },

  //处理未选择sku条目
  _setNoSelectedSkus(skuList) {
    var selectedObj = this._getSelectedSkuObj();
    var usableSkuList = this._getUsableSkus(selectedObj);

    skuList.forEach((group) => {
      group.skuArr.forEach(function(skuItem) {
        var uSkus = usableSkuList[group.text];
        skuItem.disabled = uSkus.indexOf(skuItem.text) == -1;
      });
    });

    return skuList;
  },

  //处理已选择sku条目
  _setSelectedSkus(skuList) {
    if (!(skuList && (skuList instanceof Array))) {
      return skuList;
    }
    skuList.forEach((group) => {
      var hasSelected = group.skuArr.some(function(skuItem) {
        if (skuItem.selected) {
          return true;
        }
      });

      if (!hasSelected) {
        return;
      }
      var selectedObj = this._getSelectedSkuObj(group.text);
      var usableSkuList = this._getUsableSkus(selectedObj);

      group.skuArr.forEach((skuItem) => {
        var uSkus = usableSkuList[group.text];
        skuItem.disabled = uSkus.indexOf(skuItem.text) == -1;
      })
    });
    return skuList;
  },

  /**
   * 获取可用sku项
   * @param  {[type]} skuObj [已选择的sku或假设已选择的sku]
   * @return {[type]}        [description]
   */
  _getUsableSkus(skuObj) {
    var skuJson = JSON.parse(this.data.curGoods.skuJson);
    var skuObjStr = JSON.stringify(skuObj);
    var usableSkuList = {};

    skuObjStr = skuObjStr.replace(/\{([^\}]*)\}/, '$1')

    skuJson.forEach((skuItem) => {
      var skuValue = skuItem.skuValue;

      if (skuValue.indexOf(skuObjStr) > -1) {
        var obj = JSON.parse(skuValue);

        Object.keys(obj).forEach((key) => {
          var group = usableSkuList[key];
          var skuText = obj[key];

          if (group) {
            if (group.indexOf(skuText) == -1) {
              group.push(skuText);
            }
          } else {
            usableSkuList[key] = [skuText];
          }
        })
      }
    });
    return usableSkuList;
  },

  /**
   * 获取选中sku，指定sku组除外
   * @param  {[type]} exceptSkuRow [description]
   * @return {[type]}              [description]
   */
  _getSelectedSkuObj(exceptSkuRow) {
    var skuList = this.data.curGoods.skuList || [];
    var selectedObj = {};

    skuList.forEach(function(group) {
      if (!exceptSkuRow || group.text != exceptSkuRow) {
        group.skuArr.some(function(skuItem) {
          if (skuItem.selected) {
            selectedObj[group.text] = skuItem.text;
            return true;
          }
        });
      }
    });
    return selectedObj;
  },

});